package com.chaoxuan.uebt.utils;

import com.chaoxuan.uebt.model.Result;
import com.chaoxuan.uebt.service.APIService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by fushizhe on 2017/3/13.
 */

public class RetrofitUtils {

    private static final String BASE_URL="http://www.chaoxuan.io/";

    private static APIService apiService;

    private static OkHttpClient okHttpClient;

    private static Gson gson;

    public static APIService getAPIService() {
        if(apiService==null) {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(getOkHttpClient())
                    .addConverterFactory(GsonConverterFactory.create(getGson()))
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
            apiService = retrofit.create(APIService.class);
        }
        return apiService;
    }

    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            long time=15 *1000;
            okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(time, TimeUnit.MILLISECONDS)
                    .readTimeout(time, TimeUnit.MILLISECONDS)
                    .writeTimeout(time, TimeUnit.MILLISECONDS)
                    .addNetworkInterceptor(loggingInterceptor)
//                    .addInterceptor(loggingInterceptor)
                    .build();
        }
        return okHttpClient;
    }

    public static Gson getGson(){
        if(gson==null)
            gson=new GsonBuilder().registerTypeAdapter(Result.class,new StringNullAdapter()).setLenient().create();
        return gson;
    }
}
